﻿using System.IO;
using System.Net;
using UnityEngine;
using UnityEngine.Networking;

public class AssetHandler : DownloadHandlerScript {
    private string _remoteFile;
    private string _tempFileURL;

    /// <summary>
    /// 已经下载大小
    /// </summary>
    private int _bytesTotal = 0;
    public int BytesLoaded
    {
        get
        {
            return _bytesLoaded;
        }
    }
    private int _bytesLoaded = 0;

    /// <summary>
    /// 需要下载文件总大小
    /// </summary>
    public int BytesTotal
    {
        get
        {
            return _bytesTotal;
        }
    }

    Stream localFileStram = null;


    public AssetHandler(string remoteFile,string tempFile)
    {
        this._remoteFile = remoteFile;
        this._tempFileURL = tempFile;

        HttpWebRequest tmprequest = (HttpWebRequest)WebRequest.Create(remoteFile);
        HttpWebResponse tmpresponse = (HttpWebResponse)tmprequest.GetResponse();
        _bytesTotal = (int)tmpresponse.ContentLength;
        tmprequest.Abort();
        tmpresponse.Close();


        if (File.Exists(_tempFileURL))
        {
            localFileStram = File.OpenWrite(_tempFileURL);
            //读取已存在字节
            _bytesLoaded = (int)localFileStram.Length;
            //移动指针到当前位置
            localFileStram.Seek(_bytesLoaded, SeekOrigin.Current);
        }
        else
        {
            localFileStram = new FileStream(_tempFileURL, FileMode.Create);
            _bytesLoaded = 0;
            localFileStram.Seek(_bytesLoaded, SeekOrigin.Current);
        }

        Debug.Log("已下载文件大小:" + _bytesLoaded + "/" + _bytesTotal);
    }

    protected override void ReceiveContentLength(int contentLength)
    {
        base.ReceiveContentLength(contentLength);
        _bytesTotal = contentLength;
    }

    protected override bool ReceiveData(byte[] data, int dataLength)
    {
        if (dataLength == 0)
        {
            return false;
        }
        localFileStram.Write(data, 0, dataLength);
        _bytesLoaded += dataLength;
         return true;
    }

    protected override void CompleteContent()
    {
        base.CompleteContent();
       
    }

    public void OnDispose()
    {
        localFileStram.Close();
        localFileStram.Dispose();
        localFileStram = null;
    }
}
